import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/components/Login'
import Home from '@/components/Home'
import Welcome from '@/components/Welcome'
import UserInfo from '@/components/user/UserInfo'
import Password from '@/components/user/Password'
import ExchangePoint from '@/components/point/ExchangePoint'
import ExchangeGoods from '@/components/point/ExchangeGoods'
import Appointment from '@/components/reservation/Appointment'
import AppointmentLog from '@/components/reservation/AppointmentLog'
import VolunteerActivities from '@/components/volunteer/VolunteerActivities'
import Problem from '@/components/problem/Problem'
import NotFound from '@/components/error-page/404'
import { getToken } from '@/utils/auth'
Vue.use(VueRouter)
const whiteList = ['/login', '/register']
const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children:
    [
      { path: '/welcome', component: Welcome },
      { path: '/userInfo', component: UserInfo },
      { path: '/password', component: Password },
      { path: '/pointExchange', component: ExchangePoint },
      { path: '/goodsExchange', component: ExchangeGoods },
      { path: '/appointment', component: Appointment },
      { path: '/appointmentLog', component: AppointmentLog },
      { path: '/volunteerActivities', component: VolunteerActivities },
      { path: '/problem', component: Problem }
    ]
  },
  {
    path: '/:catchAll(.*)',
    name: 'not-found',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/home' })
    } else {
      next()
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
    }
  }
})

export default router
